import java.util.HashMap;
import java.util.Map;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class Solution {
    Map<Integer, Integer> map;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        map = new HashMap<>();
        for(int i = 0; i < inorder.length; i++){
            map.put(inorder[i], i);
        }
        return findNode(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1);
    }
    public TreeNode findNode(int[] inorder, int inBegin, int inEnd, int[] postorder, int postBegin, int postEnd) {
        if(inBegin > inEnd || postBegin > postEnd){
            return null;
        }
        int index =map.get(postorder[postEnd]);

        int lenOfLeft = index - inBegin;
        TreeNode root = new TreeNode(postorder[postEnd]);
        root.left = findNode(inorder, inBegin, index-1, postorder, postBegin, postBegin + lenOfLeft-1);
        root.right = findNode(inorder, index+1, inEnd, postorder,postBegin + lenOfLeft ,postEnd-1);
        return root;
    }
}